//
//  CalendarViewController.m
//  YouthOlympic2014
//
//  Created by xiangpaopao on 14-6-20.
//  Copyright (c) 2014年 mitian. All rights reserved.
//

#import "CalendarViewController.h"
#import "DayCell.h"
#import "NSString+FontAwesome.h"
#import "UIViewController+MMDrawerController.h"
#import "AppUtils.h"

@interface CalendarViewController ()

@property (nonatomic, strong)UIViewController *leftCtrl;
@property (nonatomic, strong)UIViewController *rightCtrl;

@end

@implementation CalendarViewController
@synthesize todayDisplaylb;

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    //height:44 + 50 + 114
    self.eventListViewOffset = 0;
    
    _dayArr = [NSArray arrayWithObjects:@"10",@"11",@"12",@"13",@"14",@"15",@"16",@"17",@"18",@"19",@"20",@"21",@"22",@"23",@"24",@"25",@"26",@"27",@"28",@"29",@"30", nil];

    //self.eventListView.tableHeaderView = self.calendarView;

    
    _isCalendarShowFull = YES;
    self.isReloadDataWithCompletion = YES;
    
    //[self.calendarView setTranslatesAutoresizingMaskIntoConstraints:YES];
    [self.calendarView setFrame:CGRectMake(0, 0, ScreenWidth, CALENDARVIEW_HEIGHT)];
    [self.conView setFrame:CGRectMake(0, 0, ScreenWidth, 500)];
    //
    _todayStr = [NSString stringWithFormat:@"%ld", (long)[AppUtils getCurDayInYogRange]]; //@"20";
    self.todayDisplaylb.text = [NSString stringWithFormat:@"2014-08-%@",_todayStr];
    
    //
    self.HUD = [[MBProgressHUD alloc] initWithView:self.view];
    self.HUD.mode = MBProgressHUDModeText;
    [self.view addSubview:self.HUD];
    
    //TODO: 设置这个属性才能控制eventListView的高度，但是运行期xode会有警告，有没有其他方法呢
    [self.eventListView setTranslatesAutoresizingMaskIntoConstraints:YES];

}

- (void)setCtrlBackBtn
{
    [self setupLeftButton];
    self.leftCtrl = self.mm_drawerController.leftDrawerViewController;
    self.rightCtrl = self.mm_drawerController.rightDrawerViewController;
    self.mm_drawerController.leftDrawerViewController = nil;
    self.mm_drawerController.rightDrawerViewController = nil;
    self.navigationController.interactivePopGestureRecognizer.enabled = YES;
}

-(void)setupLeftButton{
    UIButton* leftButton= [[UIButton alloc] initWithFrame:CGRectMake(0, 0, 44, 44)];
    [leftButton setContentHorizontalAlignment:UIControlContentHorizontalAlignmentLeft];
    [leftButton.titleLabel setFont:[UIFont fontWithName:kFontAwesomeFamilyName size:26]];
    [leftButton setTitle:[NSString fontAwesomeIconStringForIconIdentifier:@"fa-angle-left"] forState:UIControlStateNormal];
    [leftButton addTarget:self action:@selector(leftButtonPress:) forControlEvents:UIControlEventTouchUpInside];
    UIBarButtonItem* leftDrawerButton = [[UIBarButtonItem alloc] initWithCustomView:leftButton];
    
    [self.navigationItem setLeftBarButtonItem:leftDrawerButton animated:YES];
}

-(void)leftButtonPress:(id)sender{
    //
    [self.navigationController popViewControllerAnimated:YES];
    self.mm_drawerController.leftDrawerViewController = self.leftCtrl;
    self.mm_drawerController.rightDrawerViewController = self.rightCtrl;
}

-(void)fixListViewHeight
{
    //解决数据少时tableview滑动的bug
    if ([self.timeline count] > 0) {

        UIView *hdView = self.eventListView.tableHeaderView;
        CGRect hdFrame = hdView.frame;
        [hdView setFrame:CGRectMake(hdFrame.origin.x,hdFrame.origin.y,hdFrame.size.width,0)];
        self.eventListView.tableHeaderView = hdView;
        [self.eventListView.tableHeaderView setHidden:YES];
        
        UIView *ftView = self.eventListView.tableFooterView;
        CGRect ftFrame = ftView.frame;
        [self.eventListView.tableFooterView setHidden:NO];
        
        //height > contentSize
        if (self.eventListView.frame.size.height>[self.timeline count] * TIMELINE_CELL_HEIGHT) {
            [ftView setFrame:CGRectMake(ftFrame.origin.x,
                                        ftFrame.origin.y,
                                        ftFrame.size.width,
                                        self.eventListView.frame.size.height - [self.timeline count] * TIMELINE_CELL_HEIGHT + 70)];
        }else{
            [ftView setFrame:CGRectMake(ftFrame.origin.x,ftFrame.origin.y,ftFrame.size.width,50)];
        }
        self.eventListView.tableFooterView = ftView;
    }else{
        UIView *ftView = self.eventListView.tableFooterView;
        CGRect ftFrame = ftView.frame;
        [ftView setFrame:CGRectMake(ftFrame.origin.x,ftFrame.origin.y,ftFrame.size.width,0)];
        self.eventListView.tableFooterView = ftView;
        [self.eventListView.tableFooterView setHidden:YES];
        
        
        UIView *hdView = self.eventListView.tableHeaderView;
        CGRect hdFrame = hdView.frame;
        [hdView setFrame:CGRectMake(hdFrame.origin.x,hdFrame.origin.y,hdFrame.size.width,self.eventListView.frame.size.height+101)];
        self.eventListView.tableHeaderView = hdView;
        [self.eventListView.tableHeaderView setHidden:NO];
    }
}

-(void) viewDidAppear:(BOOL)animated{
    [super viewDidAppear:animated];
}

-(void) viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    [self.miniCalendarView setHidden:YES];
    //self.eventListView.frame = CGRectMake(0, 170, ScreenWidth, ScreenHeight - 214 -33 - self.eventListViewOffset);
    [self fixListViewHeight];
    [self.eventListView setFrame:CGRectMake(0, 33, ScreenWidth, ScreenHeight - self.eventListViewOffset -160)];
}

-(void)initSelectedDay{
    //用动画块的方式实现延迟选中日期，默认当天
    [UIView animateWithDuration:0.0 animations:^(){
        
    }completion:^(BOOL finished){
        NSInteger curDay = [AppUtils getCurDayInYogRange];
        [self.calendarView selectItemAtIndexPath:[NSIndexPath indexPathForRow:(curDay - dayOffset) inSection:0]
                                        animated:NO scrollPosition:UICollectionViewScrollPositionNone];
        [self.miniCalendarView selectItemAtIndexPath:[NSIndexPath indexPathForRow:(curDay - dayOffset) inSection:0]
                                            animated:NO scrollPosition:UICollectionViewScrollPositionNone];
        self.selectedDayIndex = (curDay - dayOffset);
    }];
}



#pragma mark - collectionView delegate & datasource

- (NSInteger)collectionView:(UICollectionView *)view numberOfItemsInSection:(NSInteger)section;
{

    return [_dayArr count];
}

- (UICollectionViewCell *)collectionView:(UICollectionView *)cv cellForItemAtIndexPath:(NSIndexPath *)indexPath;
{
    DayCell *cell = [cv dequeueReusableCellWithReuseIdentifier:@"dayCell" forIndexPath:indexPath];
    NSString *dayStr = [_dayArr objectAtIndex:indexPath.row];
    
    NSInteger curDay = [AppUtils getCurDayInYogRange];
    
    if (indexPath.row<=3 || indexPath.row>=19) {
        [cell setDisabled:YES];
    }else{
        [cell setDisabled:NO];
//        if ((indexPath.row == (curDay - dayOffset)) && self.calendarLoadDataCount<4) {
//            //NSLog(@"index :%d",self.selectedDayIndex);
//            [self.calendarView selectItemAtIndexPath:indexPath animated:YES scrollPosition:UICollectionViewScrollPositionNone];
//            [self.miniCalendarView selectItemAtIndexPath:indexPath animated:YES scrollPosition:UICollectionViewScrollPositionNone];
//            [cell setSelected:YES];
//            self.selectedDayIndex = indexPath.row;
//            NSLog(@"calendarLoadDataCount s :%d",self.calendarLoadDataCount);
//            self.calendarLoadDataCount++;
//        }
    }
    [cell.textLabel setText:dayStr];
    //NSLog(@"self.dateMarks is %@",self.dateMarks);
    [cell setHasMatch:NO];
    for (NSNumber* mark in self.dateMarks) {
        if ([[NSString stringWithFormat:@"%@",mark] isEqualToString:dayStr]) {
            [cell setHasMatch:YES];
        }else{
            
        }
    }
    return cell;
}

- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath
{
    
    self.selectedDayIndex = indexPath.row;
    //NSLog(@"selected %d",indexPath.row);
    if (collectionView == self.calendarView) {
        int scale = floor(self.selectedDayIndex/7);
        [self.miniCalendarView selectItemAtIndexPath:indexPath animated:NO scrollPosition:UICollectionViewScrollPositionNone];
        [self.miniCalendarView setContentOffset:CGPointMake(scale*ScreenWidth , 0)];
    }else if(collectionView == self.miniCalendarView){
        [self.calendarView selectItemAtIndexPath:indexPath animated:NO scrollPosition:UICollectionViewScrollPositionNone];
    }
    
    self.todayDisplaylb.text = [NSString stringWithFormat:@"2014-08-%@",[_dayArr objectAtIndex:indexPath.row]];
}

- (void)collectionView:(UICollectionView *)collectionView didDeselectItemAtIndexPath:(NSIndexPath *)indexPath
{
    UICollectionViewCell *cell = [collectionView cellForItemAtIndexPath:indexPath];
    [cell setSelected:NO];
}

#pragma mark UIScrollView Delegate

- (void)scrollViewDidScroll:(UIScrollView *)scrollView
{
    if ([scrollView isKindOfClass:[UITableView class]]) {
        float offsetY = scrollView.contentOffset.y;
        //NSLog(@"offsetY %f",offsetY);
        if (offsetY <= 1 && !self.isCalendarShowFull) {
            [self showFullCalendar:YES];
        }else if((offsetY > 1 && self.isCalendarShowFull)){
            [self showFullCalendar:NO];
        }
    }
    
}


- (void)initEventList{
    [self.eventListView setContentOffset:(CGPointMake(0, 0.5))animated:YES];
    
}


-(void)showFullCalendar:(BOOL)full
{
    int scale = floor(self.selectedDayIndex/7);
    if (full&&self.isReloadDataWithCompletion) {
        NSLog(@"展开日历");
        self.isCalendarShowFull = YES;
        [self.miniCalendarView setHidden:YES];
        [UIView animateWithDuration:.3
                              delay:0
                            options:UIViewAnimationOptionCurveLinear animations:^{
                                self.calendarView.frame = CGRectMake(0, 50-1, ScreenWidth, CALENDARVIEW_HEIGHT);
                                self.calendarHeaderView.frame = CGRectMake(0, 0, ScreenWidth, HEADVIEW_HEIGHT);
                                self.conView.frame = CGRectMake(0, 170, ScreenWidth, CONVIEW_HEIGHT);
                                
                            }
                         completion:^(BOOL finished){
                             
                         }];
    }else{
        NSLog(@"收起日历");
        self.isCalendarShowFull = NO;
        [UIView animateWithDuration:.3
                              delay:0
                            options:UIViewAnimationOptionCurveLinear animations:^{
                                self.calendarView.frame = CGRectMake(0, -38 * scale + 20, ScreenWidth, CALENDARVIEW_HEIGHT);
                                self.calendarHeaderView.frame = CGRectMake(0, -30, ScreenWidth, HEADVIEW_HEIGHT);
                                self.conView.frame = CGRectMake(0, 63, ScreenWidth, CONVIEW_HEIGHT);
                            }
                         completion:^(BOOL finished){
                             [self.miniCalendarView setHidden:NO];
                             [self.miniCalendarView setContentOffset:CGPointMake(scale*ScreenWidth , 0)];
                         }];
    }
}

- (void)reloadCalendarData
{
    [self.calendarView reloadData];
    [self.miniCalendarView reloadData];
    [self initSelectedDay];
}
-(void)reloadEventData
{
    //防止点击日期时展开日历
    [UIView animateWithDuration:0.33 animations:^(){
        //
        self.isReloadDataWithCompletion = NO;
        [self.eventListView reloadData];
        [self fixListViewHeight];
        [self initEventList];
    }completion:^(BOOL finished){
        self.isReloadDataWithCompletion = YES;
    }];
}


@end
